package com.neuedu.elmserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neuedu.elmserver.mapper.FoodMapper;
import com.neuedu.elmserver.mapper.ReviewMapper;
import com.neuedu.elmserver.pojo.Food;
import com.neuedu.elmserver.pojo.Review;
import com.neuedu.elmserver.service.ReviewService;
import com.neuedu.elmserver.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 评价表 服务实现类
 * </p>
 */
@Service
public class ReviewServiceImpl extends ServiceImpl<ReviewMapper, Review> implements ReviewService {

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private FoodMapper foodMapper; // 注入 FoodMapper

    /**
     * 根据用户编号查询评价列表
     * @param userId 用户 ID
     * @return ResultVO 包含查询结果
     */
    @Override
    public ResultVO getReviewsByUserId(Integer userId) {
        QueryWrapper<Review> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId); // 假设 Review 表中有 user_id 字段

        List<Review> reviews = reviewMapper.selectList(queryWrapper);

        if (reviews.isEmpty()) {
            return ResultVO.fail("没有找到相关评价");
        }

        List<Map<String, Object>> reviewList = new ArrayList<>();
        for (Review review : reviews) {
            // 根据食品 ID 查询食品信息
            Food food = foodMapper.selectById(review.getFoodId());
            String foodImg = (food != null) ? food.getFoodImg() : null; // 获取食品图片
            String foodName = (food != null) ? food.getFoodName() : null; // 获取食品图片

            // 创建一个 Map 来存储评价和食品信息
            Map<String, Object> reviewInfo = new HashMap<>();
            reviewInfo.put("reviewId", review.getReviewId());
            reviewInfo.put("foodId", review.getFoodId());
            reviewInfo.put("userId", review.getUserId());
            reviewInfo.put("rating", review.getRating());
            reviewInfo.put("comment", review.getComment());
            reviewInfo.put("reviewDate", review.getReviewDate());
            reviewInfo.put("foodImg", foodImg); // 设置食品图片
            reviewInfo.put("foodName", foodName);

            reviewList.add(reviewInfo);
        }

        return ResultVO.ok("查询成功", reviewList);
    }
}
